package com.lx.index.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.bean.Result;
import com.lx.dm.entity.Category;
import com.lx.dm.entity.Product;
import com.lx.dm.entity.User;
import com.lx.index.web.feign.OtherAction;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;

import java.util.List;

@RestController
public class IndexDo {

    @RequestMapping("index")
    String index(HttpServletRequest request){
        return "index" + request.getServerPort();
    }

    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("index-other")
    String other(){
        return restTemplate.getForObject("http://cloud-others/others", String.class);
    }


    @Autowired
    OtherAction otherAction;

    @RequestMapping("hots")
    List<Product> queryHots(){
        ObjectMapper mapper = new ObjectMapper();
        try(Jedis jedis = new Jedis("host.docker.internal", 6380); ){

            // 默认访问本机6379
            String key = "cloud_dm_home_hots";
            System.out.println("存储redis缓存数据");
            List<Product> hots = otherAction.queryHots();
            String json = mapper.writeValueAsString(hots);
            jedis.set(key, json);
            return hots;
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("getCate")
    List<Category> getCate(){
        return otherAction.getCate();
    }

    @RequestMapping("getNews")
    List<Product> getNews(){
        return otherAction.queryNews();
    }

    @RequestMapping("getProductById")
    Product getProductById(Integer pid){
        return otherAction.getProductById(pid);
    }













    ///////////////////////////////////////////////////

    // 高版本JDK加@RequestParam()
    @RequestMapping("add")
    int add(@RequestParam("a") int a,
            @RequestParam("b") int b){
        return otherAction.add(a,b);
    }

    // 对象属性映射为请求参数名 自动装箱
    @RequestMapping("res")
    Result res(Result r){
        r.setCode(r.getCode() + 1);
        return otherAction.res(r);
    }

    // 用户信息通过 请求体body 传递过来
    @RequestMapping("user")
    User user(@RequestBody User user,
              @RequestParam("myname") String myname){
        user.setName(myname);
        return otherAction.user(user, myname);
    }

    // RESTful 请求方式的地址参数
    @RequestMapping("hello/{nm}")
    String hello(@PathVariable("nm") String name){
        return otherAction.hello(name);
    }
}
